package com.sport.facilities.booking.system;

import java.util.List;

import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.sport.facilities.booking.system.R.color;
import com.sport.facilities.booking.system.R.xml;
import com.sport.facilities.booking.system.httptask.OnTaskCompleted;
import com.sport.facilities.booking.system.httptask.TransferBookingFormResultTask;
import com.sport.facilities.booking.system.httptask.TransferBookingPageTask;
import com.sport.facilities.booking.system.httptask.TransferBookingResultTask;
import com.sport.facilities.booking.system.model.Booking;
import com.sport.facilities.booking.system.model.BookingRequestModel;
import com.sport.facilities.booking.system.ui.DialogHelper;
import com.sport.facilities.booking.system.ui.YesAction;

public class TransferBookingActivity extends Activity {
	private static final String TAG = "TransferBookingActivity";
	final Context context = this;

	final TransferBookingActivity transActivity = this;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transfer_booking);

	}

	@Override
	public void onResume() {
		super.onResume();
		fnLoadTransferBookData();
	}

	protected void onPause() {
		//End the current activity while onpause
		finish();
		super.onPause();
	}

	protected void fnSetTransferBooking(List<Booking> bookingList) {
		if (bookingList.size() > 0) {

			TableLayout tbl = (TableLayout) findViewById(R.id.transfer_booking_table);
			TextView[][] tvs;
			TableRow[] tbrs;
			tvs = new TextView[bookingList.size()][6];
			tbrs = new TableRow[bookingList.size() + 1];
			int count = bookingList.size();
			for (int i = 0; i < count; i++) {
				Booking bkk = (Booking) bookingList.get(i);
				tbrs[i] = new TableRow(this);
				tbrs[i].setTag(bkk.getId());

				if (i % 2 == 0) {
					tbrs[i].setBackgroundResource(R.color.color_white);
				} else {
					tbrs[i].setBackgroundResource(R.color.color_normal_grey);
				}
				tbrs[i].setBackgroundResource(drawable.list_selector_background);

				tbrs[i].setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						if (v instanceof TableRow) {
							TableRow row = (TableRow) v;
							TextView transferid = (TextView) row.getChildAt(5);
							TextView activity = (TextView) row.getChildAt(4);
							TextView date = (TextView) row.getChildAt(0);
							TextView time = (TextView) row.getChildAt(1);
							TextView centre = (TextView) row.getChildAt(2);
							// Log.d(TAG, "2. Clicked " + child.getText());
							// Log.d(TAG, "2. Clicked " + cancelid.getText());

							final BookingRequestModel bkmodel = new BookingRequestModel();
							bkmodel.setId((String) transferid.getText());
							Log.d(TAG, "Transfer Record with Transfer ID : "
									+ bkmodel.getId() + "?");

							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
									context);

							// set title
							alertDialogBuilder.setTitle("Transfer Booking");

							// set dialog message
							alertDialogBuilder
									.setMessage(
											"Date:      " + date.getText()
													+ "\n" + "Time:     "
													+ ((String) time.getText()).replaceAll("\n to \n", "-") + "\n"
													+ "Centre:   "
													+ centre.getText() + "\n"
													+ "Activity: "
													+ ((String) activity.getText()).replaceAll("\n", " ") + "\n")

									.setCancelable(false)
									.setPositiveButton(
											"Yes",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													OnTaskCompleted completeAction = new OnTaskCompleted() {
														public void onTaskCompleted(
																Object resultList) {
														}

														public void onTaskFailed(
																String errMessage) {
														}
													};

													OnTaskCompleted completeAction2 = new OnTaskCompleted() {

														public void onTaskCompleted(
																Object formResult) {
															// TODO
															// Auto-generated
															// method stub
															// removetbr(); //
															// remove
															// table
															// rows
															// onResume(); //
															// reload
															// the
															// data
															// to
															// table
															// call a function
															// to create
															// transfer booking
															// form
															List<Booking> formResultList = (List<Booking>) formResult;
															Log.d(TAG,
																	"onTaskCompleted, Transfer bookings form:"
																			+ formResultList
																					.toString());
															fnCreatetbtable(formResultList);

														}

														public void onTaskFailed(
																String errMessage) {
															fndialogMess("Fail to transfer booking.");
														}

													};

													TransferBookingResultTask tbpTask = new TransferBookingResultTask(
															context,
															completeAction2);
													tbpTask.fnTransferBook(bkmodel);

												}
											})
									.setNegativeButton(
											"No",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													// if this button is
													// clicked, just close
													// the dialog box and do
													// nothing
													dialog.cancel();
												}
											});
							// create alert dialog
							AlertDialog alertDialog = alertDialogBuilder
									.create();
							// show it
							alertDialog.show();

						}

					}
				});
				tvs[i][1] = new TextView(this);
				tvs[i][1].setTag("date" + i);// setting tag with index i
				tvs[i][1].setText(bkk.getDate().substring(0, bkk.getDate().length() - 5));
				tvs[i][1].setTextSize(12);
				tvs[i][1].setWidth(40);
				//tvs[i][1].setBackgroundColor(Color.BLUE);
				tvs[i][1].setHeight(120);
				tvs[i][1].setGravity(Gravity.CENTER_HORIZONTAL);
				// rowspan[i].addView(tvs[i][0]);
				tbrs[i].addView(tvs[i][1]);

				tvs[i][2] = new TextView(this);
				tvs[i][2].setTag("time" + i);// setting tag with index i
				tvs[i][2].setText(bkk.getTime());
				tvs[i][2].setTextSize(12);
				tvs[i][2].setWidth(160);
				tvs[i][2].setHeight(120);
				//tvs[i][2].setBackgroundColor(Color.GREEN);
				tvs[i][2].setGravity(Gravity.CENTER_HORIZONTAL);
				// rowspan[i].setPadding(0, 20, 0, 0);
				// rowspan[i].addView(tvs[i][1]);

				tbrs[i].addView(tvs[i][2]);

				// tbrs[i].addView(rowspan[i]);

				tvs[i][3] = new TextView(this);
				tvs[i][3].setTag("centre" + i);// setting tag with index i
				tvs[i][3].setText(bkk.getCentre());
				tvs[i][3].setTextSize(12);
				tvs[i][3].setWidth(190);
				tvs[i][3].setHeight(120);
				//tvs[i][3].setBackgroundColor(Color.BLUE);
				tvs[i][3].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][3].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][3]);

				tvs[i][4] = new TextView(this);
				tvs[i][4].setTag("court" + i);// setting tag with index i
				tvs[i][4].setText(bkk.getCourt());
				tvs[i][4].setTextSize(12);
				tvs[i][4].setWidth(55);
				tvs[i][4].setHeight(120);
				//tvs[i][4].setBackgroundColor(Color.GREEN);
				tvs[i][4].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][4].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][4]);

				tvs[i][5] = new TextView(this);
				tvs[i][5].setTag("activity" + i);// setting tag with index i
				String tmpActivity = bkk.getActivity().replaceAll("  ", "\n");
				tmpActivity = tmpActivity.replaceAll(" ", "\n");
				tvs[i][5].setText(tmpActivity);
				tvs[i][5].setTextSize(12);
				tvs[i][5].setWidth(130);
				tvs[i][5].setHeight(120);
				//tvs[i][5].setBackgroundColor(Color.YELLOW);
				tvs[i][5].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][5].setPadding(0, 20, 0, 0);
				tbrs[i].addView(tvs[i][5]);

				tvs[i][0] = new TextView(this);
				tvs[i][0].setTag("id" + i);// setting tag with index i
				tvs[i][0].setText(bkk.getId());
				tvs[i][0].setWidth(0);
				tvs[i][0].setHeight(0);
				tvs[i][0].setTextSize(0);
				
				//tvs[i][0].setGravity(Gravity.CENTER_HORIZONTAL);
				tvs[i][0].setVisibility(View.INVISIBLE);
				// rg.addView(rds[i]);
				tbrs[i].addView(tvs[i][0]);

				tbrs[i].setGravity(Gravity.CENTER_HORIZONTAL);

				tbl.addView(tbrs[i]);

			}
			tbrs[count] = new TableRow(this);
			tbrs[count].setBackgroundResource(R.color.color_deep_blue);
			TextView emptytvs;
			emptytvs = new TextView(this);

			emptytvs = new TextView(this);
			emptytvs.setTag("empty");// setting tag with index i
			emptytvs.setText("");
			emptytvs.setTextSize(10);
			emptytvs.setWidth(100);
			emptytvs.setHeight(30);
			emptytvs.setGravity(Gravity.CENTER);
			tbrs[count].addView(emptytvs);
			tbl.addView(tbrs[count]);
		} else {
			DialogHelper
					.getOkAlertDialog(this, "No record has been found.", "")
					.show();
		}

	}

	private void fnLoadTransferBookData() {

		// remove old table rows for resume();
		removetbr(1);

		final TransferBookingActivity tbActivity = this;
		OnTaskCompleted completeAction = new OnTaskCompleted() {
			public void onTaskCompleted(Object resultList) {
				Log.d(TAG, "onTaskCompleted, Transfer bookings table:"
						+ resultList.toString());
				List<Booking> bookingList = (List<Booking>) resultList;
				tbActivity.fnSetTransferBooking(bookingList);
			}

			public void onTaskFailed(String errMessage) {
				Log.e(TAG, errMessage);
				

				YesAction yesAction = new YesAction() {
					public void fnDoYesAction() {
						finish();
					}
				};
				
				DialogHelper
				.getOkActionDialog(
						transActivity,
						"Transfer Booking",
						"No record has been found.",
						yesAction)
				.show();
				
				//Toast.makeText(tbActivity,
				//		"Error loading booking...\n" + errMessage,
				//		Toast.LENGTH_LONG).show();
			}
		};
		TransferBookingPageTask tbTask = new TransferBookingPageTask(this,
				completeAction);
		tbTask.fnGetTransferBookingList();
	}

	public void fnCreatetbtable(List<Booking> formList) {

		final TransferBookingActivity tbActivity = this;
		// Destroy the current table
		// TableLayout tbl = (TableLayout)
		// findViewById(R.id.transfer_booking_table);
		// tbl.removeAllViews();
		removetbr(0);

		// TextView[] tvs;
		// TableRow[] tbrs;
		// tvs = new TextView[14];
		// tbrs = new TableRow[8];

		// Create Form table in transfer booking table

		if (formList.size() > 0) {
			final Booking bkk = (Booking) formList.get(0);

			LinearLayout ll = new LinearLayout(this);
			ll.setOrientation(LinearLayout.VERTICAL);

			TableLayout titleTable = new TableLayout(this);
			TableRow row0 = new TableRow(this);
			titleTable.setPadding(0, 14, 0, 0);
			ImageView tbTitle = new ImageView(this);
			//tbTitle.setImageResource(R.drawable.transferbooking);
			
			//ImageView img=(ImageView)findViewById(R.id.ImageView01);
		    Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.transferbooking);
		    int width=483;
		    int height=64;
		    Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true);
		    tbTitle.setImageBitmap(resizedbitmap);
			
			//tbTitle.setText("Transfer Booking");
			//tbTitle.setTextSize(19);
			//tbTitle.setWidth(479);
			// tbTitle.setLayoutParams(new
			// LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

			//tbTitle.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
			row0.addView(tbTitle);
			titleTable.addView(row0);

			ll.addView(titleTable);

			TableLayout formTable = new TableLayout(this);
			formTable.setId(R.id.transbook_form_table);
			// formTable.setLayoutParams(new
			// TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
			// TableRow.LayoutParams.FILL_PARENT));
			// formTable.setStretchAllColumns(true);

			formTable.setPadding(30, 20, 30, 0);
			// Create the first row and add two text views

			TableRow row1 = new TableRow(this);
			TextView text1 = new TextView(this);
			text1.setText("User No. : ");
			text1.setWidth(150);
			text1.setHeight(50);
			text1.setTextSize(13);
			text1.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text1.setPadding(10, 0, 0, 0);
			TextView text2 = new TextView(this);
			text2.setText(bkk.getUserId());
			text2.setWidth(240);
			text2.setHeight(50);
			text2.setTextSize(13);
			text2.setGravity(android.view.Gravity.CENTER_VERTICAL);
			row1.addView(text1);
			row1.addView(text2);
			row1.setBackgroundResource(R.color.color_little_orange);
			formTable.addView(row1);

			TableRow row2 = new TableRow(this);
			TextView text3 = new TextView(this);
			text3.setText("Centre : ");
			text3.setWidth(150);
			text3.setHeight(50);
			text3.setTextSize(13);
			text3.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text3.setPadding(10, 0, 0, 0);
			TextView text4 = new TextView(this);
			text4.setText(bkk.getCentre());
			text4.setWidth(240);
			text4.setHeight(50);
			text4.setTextSize(13);
			text4.setGravity(android.view.Gravity.CENTER_VERTICAL);
			row2.addView(text3);
			row2.addView(text4);
			formTable.addView(row2);

			TableRow row3 = new TableRow(this);
			TextView text5 = new TextView(this);
			text5.setText("Court : ");
			text5.setWidth(150);
			text5.setHeight(50);
			text5.setTextSize(13);
			text5.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text5.setPadding(10, 0, 0, 0);
			TextView text6 = new TextView(this);
			text6.setText(bkk.getCourt());
			text6.setWidth(240);
			text6.setHeight(50);
			text6.setTextSize(13);
			text6.setGravity(android.view.Gravity.CENTER_VERTICAL);
			row3.addView(text5);
			row3.addView(text6);
			row3.setBackgroundResource(R.color.color_little_orange);
			formTable.addView(row3);

			TableRow row4 = new TableRow(this);
			TextView text7 = new TextView(this);
			text7.setText("Activity : ");
			text7.setWidth(150);
			text7.setHeight(50);
			text7.setTextSize(13);
			text7.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text7.setPadding(10, 0, 0, 0);
			TextView text8 = new TextView(this);
			text8.setText(bkk.getActivity());
			text8.setWidth(240);
			text8.setHeight(50);
			text8.setTextSize(13);
			text8.setGravity(android.view.Gravity.CENTER_VERTICAL);
			row4.addView(text7);
			row4.addView(text8);
			formTable.addView(row4);

			TableRow row5 = new TableRow(this);
			TextView text9 = new TextView(this);
			text9.setText("Date : ");
			text9.setWidth(150);
			text9.setHeight(50);
			text9.setTextSize(13);
			text9.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text9.setPadding(10, 0, 0, 0);
			TextView text10 = new TextView(this);
			text10.setText(bkk.getDate());
			text10.setWidth(240);
			text10.setHeight(80);
			text10.setTextSize(13);
			text10.setGravity(android.view.Gravity.CENTER_VERTICAL);
			row5.addView(text9);
			row5.addView(text10);
			row5.setBackgroundResource(R.color.color_little_orange);
			formTable.addView(row5);

			TableRow row6 = new TableRow(this);
			TextView text11 = new TextView(this);
			text11.setText("Time : ");
			text11.setWidth(150);
			text11.setHeight(50);
			text11.setTextSize(13);
			text11.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text11.setPadding(10, 0, 0, 0);
			TextView text12 = new TextView(this);
			text12.setText(bkk.getTime());
			text12.setWidth(240);
			text12.setHeight(50);
			text12.setTextSize(13);
			text12.setGravity(android.view.Gravity.CENTER_VERTICAL);
			row6.addView(text11);
			row6.addView(text12);
			formTable.addView(row6);

			TableRow row7 = new TableRow(this);
			TextView text13 = new TextView(this);
			text13.setText("Transfer to Student/Staff No. : ");
			text13.setWidth(150);
			text13.setHeight(120);
			text13.setTextSize(13);
			text13.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text13.setPadding(10, 0, 0, 0);

			row7.addView(text13);
			row7.setBackgroundResource(R.color.color_little_orange);

			EditText inputId = new EditText(this);
			// inputId.setWidth(10);
			inputId.setId(R.id.transbook_form_transtousrId);
			row7.addView(inputId);
			formTable.addView(row7);

			TableRow row8 = new TableRow(this);
			TextView text14 = new TextView(this);
			text14.setText("His/Her Surname : ");
			text14.setWidth(150);
			text14.setHeight(90);
			text14.setTextSize(13);
			text14.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text14.setPadding(10, 0, 0, 0);

			row8.addView(text14);

			EditText inputname = new EditText(this);
			// inputname.setWidth(10);
			inputname.setId(R.id.transbook_form_transtoName);
			row8.addView(inputname);
			formTable.addView(row8);

			TableRow row9 = new TableRow(this);
			TextView text15 = new TextView(this);
			text15.setText(" ");
			text15.setWidth(150);
			text15.setHeight(90);
			text15.setTextSize(13);
			text15.setGravity(android.view.Gravity.CENTER_VERTICAL);
			text15.setPadding(10, 0, 0, 0);

			row9.addView(text15);

			Button submitButton = new Button(this);
			// submitButton.setWidth(30);
			submitButton.setText("Submit");
			submitButton.setTextColor(Color.WHITE);
			// submitButton.setBackgroundResource();
			submitButton.setBackgroundResource(xml.btn_selector_green);

			row9.addView(submitButton);
			formTable.addView(row9);

			submitButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					boolean checkPoint = true;

					EditText etId = (EditText) findViewById(R.id.transbook_form_transtousrId);
					String checkId = etId.getText().toString();
					if (checkId.matches("")) {
						checkPoint = false;
					}

					EditText etName = (EditText) findViewById(R.id.transbook_form_transtoName);
					String checkName = etName.getText().toString();
					if (checkName.matches("")) {
						checkPoint = false;
					}

					if (!checkPoint) {
						fndialogMess("Please Input Transfer to Student/Staff No. and His/Her Surname");
					} else {

						BookingRequestModel brm = new BookingRequestModel();

						brm.setTransferId(etId.getText().toString());
						brm.setTransferSurname(etName.getText().toString());
						brm.setId(bkk.getId());

						OnTaskCompleted completeAction2 = new OnTaskCompleted() {

							public void onTaskCompleted(Object formResult) {
								YesAction yesAction = new YesAction() {
									public void fnDoYesAction() {
										// reload page
										tbActivity.reload();
									}
								};
								DialogHelper.getOkAlertDialog(tbActivity,
										"Transfer Booking",
										"Transfer successfully.", yesAction)
										.show();
							}

							public void onTaskFailed(String errMessage) {
								fndialogMess("Fail to transfer booking.");
							}

						};

						TransferBookingFormResultTask tbfTask = new TransferBookingFormResultTask(
								context, completeAction2);
						tbfTask.fnTransferBookForm(brm);

					}

				}

			});

			ll.addView(formTable);
			setContentView(ll);

		} else {
			fndialogMess("Fail to Create Transfer Booking Form.");
		}

	}

	public void removetbr(Integer rowNum) {
		if (rowNum.equals(null)) {

			rowNum = 0;
		}
		// remove table rows for reload
		TableLayout tbl = (TableLayout) findViewById(R.id.transfer_booking_table);
		int count = tbl.getChildCount();
		for (int i = rowNum; i < count; i++) {
			View child = tbl.getChildAt(i);
			if (child instanceof TableRow)
				((ViewGroup) child).removeAllViews();
		}
	}

	public void fndialogMess(String disMess) {
		// show dialog if fail to cancel
		DialogHelper.getOkAlertDialog(this, "Transfer Booking", disMess).show();

	}

	public void reload() {

		// reload this activity
		Intent intent = getIntent();
		overridePendingTransition(0, 0);
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		finish();
		overridePendingTransition(0, 0);
		startActivity(intent);

	}

}
